﻿///// <reference path="C:\File\学习\Web前端\Angluar\learnangular\Angular\Content/js/angular1.4.8.js" />
//angular.module('project', ['ngRoute', 'firebase'])

//.value('fbURL', 'https://ng-projects-list.firebaseio.com/')
//.service('fbRef', function (fbURL) {
//    return new Firebase(fbURL)
//})
//.service('fbAuth', function ($q, $firebase, $firebaseAuth, fbRef) {
//    var auth;
//    return function () {
//        if (auth) return $q.when(auth);
//        var authObj = $firebaseAuth(fbRef);
//        if (authObj.$getAuth()) {
//            return $q.when(auth = authObj.$getAuth());
//        }
//        var deferred = $q.defer();
//        authObj.$authAnonymously().then(function (authData) {
//            auth = authData;
//            deferred.resolve(authData);
//        });
//        return deferred.promise;
//    }
//})

//.service('Projects', function ($q, $firebase, fbRef, fbAuth) {
//    var self = this;
//    this.fetch = function () {
//        if (this.projects) return $q.when(this.projects);
//        return fbAuth().then(function (auth) {
//            var deferred = $q.defer();
//            var ref = fbRef.child('projects-fresh/' + auth.auth.uid);
//            var $projects = $firebase(ref);
          
//            ref.on('value', function (snapshot) {
//                if (snapshot.val() === null) {
//                    $projects.$set(window.projectsArray);
//                }
//                self.projects = $projects.$asArray();
//                deferred.resolve(self.projects);
//            });

//            //Remove projects list when no longer needed.
//            ref.onDisconnect().remove();
//            return deferred.promise;
//        });
//    };
//})

//.config(function ($routeProvider) {
//    var resolveProjects = {
//        projects: function (Projects) {
//            return Projects.fetch();
//        }
//    };

//    $routeProvider
//      .when('/', {
//          controller: 'ProjectListController as projectList',
//          templateUrl: 'list.html',
//          resolve: resolveProjects
//      })
//      .when('/edit/:projectId', {
//          controller: 'EditProjectController as editProject',
//          templateUrl: 'detail.html',
//          resolve: resolveProjects
//      })
//      .when('/new', {
//          controller: 'NewProjectController as editProject',
//          templateUrl: 'detail.html',
//          resolve: resolveProjects
//      })
//      .otherwise({
//          redirectTo: '/'
//      });
//})

//.controller('ProjectListController', function (projects) {
//    var projectList = this;
//    projectList.projects = projects;
//})

//.controller('NewProjectController', function ($location, projects) {
//    var editProject = this;
//    editProject.save = function () {
//        projects.$add(editProject.project).then(function (data) {
//            $location.path('/');
//        });
//    };
//})

//.controller('EditProjectController',
//  function ($location, $routeParams, projects) {
//      var editProject = this;
//      var projectId = $routeParams.projectId,
//          projectIndex;

//      editProject.projects = projects;
//      projectIndex = editProject.projects.$indexFor(projectId);
//      editProject.project = editProject.projects[projectIndex];

//      editProject.destroy = function () {
//          editProject.projects.$remove(editProject.project).then(function (data) {
//              $location.path('/');
//          });
//      };

//      editProject.save = function () {
//          editProject.projects.$save(editProject.project).then(function (data) {
//              $location.path('/');
//          });
//      };
//  });



(function (angular) {
    angular.module('project', ['firebase', 'ngRoute'])
    .value('fbURL', 'https://sb-plnkr.firebaseio.com/so:28942661')

    .service('fbRef', function (fbURL) {
        return new Firebase(fbURL)
    })

    .service('fbAuth', function ($q, $firebaseAuth, fbRef) {
        var auth;
        return function () {
            if (auth) return $q.when(auth);
            var authObj = $firebaseAuth(fbRef);
            if (authObj.$getAuth()) {
                return $q.when(auth = authObj.$getAuth());
            }
            var deferred = $q.defer();
            authObj.$authAnonymously().then(function (authData) {
                auth = authData;
                deferred.resolve(authData);
            });
            return deferred.promise;
        }
    })

    .service('Projects', function ($q, $firebaseArray, fbRef) {
        this.sync = $firebaseArray(fbRef);
        this.sync.$loaded().then(function (data) {
            var projects = data;
        });
        return this.sync;
    })

    .controller('ListCtrl', function ($scope, $location, Projects) {
        Projects.$loaded().then(function (data) {
            $scope.projects = data;
        });
    })

    .controller('CreateCtrl', function ($scope, $location, Projects) {
        console.log("CreateCtrl");
        $scope.save = function () {
            console.debug("Adding");
            if ($scope.project && $scope.project.content !== '') {
                Projects.$add($scope.project).then(function (ref) {
                    console.log("Added ref", ref);
                    $location.path('/');
                }).catch(function (errorObject) {
                    console.error(errorObject);
                });
            } else {
                alert("You have to enter something.");
            }
        };
    })

    .controller('EditCtrl', function ($scope, $location, $routeParams, Projects) {
        var projectId = $routeParams.projectId,
            projectIndex;

        $scope.init = function () {
            Projects.$loaded().then(function (data) {
                $scope.projects = data;
                console.info("EditCtrl - Projects.$loaded():", data);
                projectIndex = $scope.projects.$indexFor(projectId);
                $scope.project = $scope.projects[projectIndex];
            });
        }

        $scope.destroy = function () {
            $scope.projects.$remove($scope.project).then(function (data) {
                $location.path('/');
            });
        };

        $scope.save = function () {
            $scope.projects.$save($scope.project).then(function (data) {
                $location.path('/');
            });
        };
    })

    .config(function ($routeProvider, $locationProvider) {
        $routeProvider
          .when('/', {
              controller: 'ListCtrl',
              templateUrl: 'list.html'
          })
          .when('/edit/:projectId', {
              controller: 'EditCtrl',
              templateUrl: 'detail.html'
          })
          .when('/new', {
              controller: 'CreateCtrl',
              templateUrl: 'create.html'
          })
          .otherwise({
              redirectTo: '/'
          });

        //$locationProvider.html5Mode(true);
    });
})(window.angular);